package com.pagoda.nerp.trade.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.pagoda.nerp.trade.app.vendor.dto.MdVendorGoodsDto;
import com.pagoda.nerp.trade.common.ConstantDefine;
import com.pagoda.nerp.trade.common.PageListResult;
import com.pagoda.nerp.trade.dao.MdGoodsDao;
import com.pagoda.nerp.trade.dao.MdVendorGoodsDao;
import com.pagoda.nerp.trade.entity.MdAccount;
import com.pagoda.nerp.trade.entity.MdGoods;
import com.pagoda.nerp.trade.entity.MdVendorGoods;
import com.pagoda.nerp.trade.service.MdVendorGoodsService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 供应商供应商品清单服务层接口
 *
 * Created by Jungle on 2016/12/14.
 *
 * @author Jungle
 *
 */
@Service
public class MdVendorGoodsServiceImpl implements MdVendorGoodsService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MdGoodsDao goodsDao;
    @Autowired
    MdVendorGoodsDao vendorGoodsDao;

    @Override
    public PageListResult<MdVendorGoods> listAllMdVendorGoods(Map con) {
        int pageNo = con.get("pageNo") != null ? Integer.parseInt(con.get("pageNo").toString()) : 0;
        int pageSize = con.get("pageSize") != null ?  Integer.parseInt(con.get("pageSize").toString()) : 0;
        Page<MdVendorGoods> pageInfo = PageHelper.startPage(pageNo, pageSize);
        List<MdVendorGoods> listMdVendorGoods = (List<MdVendorGoods>) vendorGoodsDao.selectAllByConditon(con);
        return new PageListResult<MdVendorGoods>(pageInfo,listMdVendorGoods);
    }

    @Override
    public MdVendorGoods findMdVendorGoodsByCon(Map con) {

        return vendorGoodsDao.selectOneByCondition(con);
    }

    /**
     * 新增水果信息
     * @param goods 发布水果表单信息,vendorId 供应商ID
     * */
    @Transactional
    @Override
    public int addGoods(MdVendorGoodsDto goods) throws Exception{
        // 1.定义水果ID
        int goodsId = 0;

        // 2.如果goodsCode为空 新增自定义水果
        if (null == goods.getGoodsCode() || "".equals(goods.getGoodsCode().trim())){

            // 2.1转换为MdGoods对象
            MdGoods mdGoods = new MdGoods();

            mdGoods.setGoodsName(goods.getGoodsName());
            mdGoods.setCreateTime(new Date());
            mdGoods.setCreateUser(getUserInfo());
            mdGoods.setModifyTime(new Date());
            mdGoods.setModifyUser(getUserInfo());
            mdGoods.setIsEnabled("Y");

            // 2.2持久化
            goodsDao.insert(mdGoods);

            goodsId = mdGoods.getGoodsId();
        } else {
            // 2.4查询goodsCode对应goodsId
            String result = goodsDao.selectByGoodsCode(goods.getGoodsCode());

            if (null == result){
                throw new Exception("未找到该水果编码！");
            }

            goodsId = Integer.parseInt(result);
        }


        // 3.转换为MdVendorGoods对象
        MdVendorGoods mdVendorGoods = new MdVendorGoods();

        mdVendorGoods.setVendorId(goods.getVendorId());
        mdVendorGoods.setGoodsId(goodsId);
        mdVendorGoods.setSpec(goods.getSpec());
        mdVendorGoods.setPrice(goods.getPrice());
        mdVendorGoods.setPacking(goods.getPacking());
        mdVendorGoods.setSupplyQty(goods.getSupplyQty());
        mdVendorGoods.setSupplyArea(goods.getSupplyArea());
        mdVendorGoods.setSupplyTime(goods.getSupplyTime());
        mdVendorGoods.setShipAddr(goods.getShipAddr());
        mdVendorGoods.setExpressType(goods.getExpressType());
        mdVendorGoods.setQualityCode(goods.getQualityCode());
        mdVendorGoods.setRemark(goods.getRemark());
        mdVendorGoods.setCreateTime(new Date());
        mdVendorGoods.setCreateUser(getUserInfo());
        mdVendorGoods.setModifyTime(new Date());
        mdVendorGoods.setModifyUser(getUserInfo());

        // 4.持久化
        int rs1 = vendorGoodsDao.insert(mdVendorGoods);

        if(rs1 <1){
            throw new Exception("新增水果失败，数据库异常！");
        }

        return mdVendorGoods.getVendorGoodsId();
    }

    /**
     * 查询水果列表
     * @param params 供应商Id
     * */
    @Override
    public PageListResult<Map<String,Object>> queryGoodsBrief(Map<String,Object> params) throws Exception{
        // 1.参数处理
        int vendorId, pageNo, pageSize = 0;
        try {
            vendorId = Integer.parseInt(params.get("vendorId").toString());
            pageNo = null == params.get("pageNo") ? 0 : Integer.parseInt(params.get("pageNo").toString());
            pageSize = null == params.get("pageSize") ? 10 : Integer.parseInt(params.get("pageSize").toString());
        } catch (NumberFormatException e){
            throw new Exception("数字格式异常！");
        }

        // 2.分页处理
        Page pageInfo = PageHelper.startPage(pageNo, pageSize, true);

        // 3.查询
        List<MdVendorGoods> vendorGoodsList= vendorGoodsDao.selectByVendorId(vendorId);

        // 4.判断结果集是否为空
        if (null == vendorGoodsList){
            return null;
        }

        // 5.MdGoods转Map
        List<Map<String,Object>> goodsList = new ArrayList<Map<String,Object>>();
        Map<String,Object> good = null;

        DateFormat df = new SimpleDateFormat(ConstantDefine.TIME_FORMAT);

        for(MdVendorGoods md : vendorGoodsList){
            good = new HashMap<String,Object>();

            good.put("goodsId", md.getGoodsId());
            good.put("goodsName", md.getGoodsName());
            good.put("goodsCode", md.getGoodsCode());
            good.put("vendorGoodsId", md.getVendorGoodsId());
            good.put("modifyTime", null == md.getModifyTime() ? "" : df.format(md.getModifyTime()));
            good.put("status", md.getQualityStatus());

            goodsList.add(good);
        }

        return new PageListResult<Map<String,Object>>(pageInfo, goodsList);
    }

    /**
     * 查看水果详情
     * @param params 水果Id,供应商Id
     * */
    @Override
    public MdVendorGoodsDto queryGoodsDetail(Map<String,Object> params) throws Exception{
        // 1.参数处理
        int vendorId, goodsId = 0;
        try {
            vendorId = Integer.parseInt(params.get("vendorId").toString());
            goodsId = null == params.get("goodsId") ? 0 : Integer.parseInt(params.get("goodsId").toString());
        } catch (NumberFormatException e){
            throw new Exception("数字格式异常！");
        }

        // 2.查询
        MdGoods mdGoods= goodsDao.selectByPrimaryKey(goodsId);
        List<MdVendorGoods> mdVendorGoodsList = vendorGoodsDao.selectAllByConditon(params);

        if (null == mdVendorGoodsList || mdVendorGoodsList.size() == 0){
            throw new Exception("未查询到相关数据！");
        }

        MdVendorGoods vendorGoods = mdVendorGoodsList.get(0);

        // 3.MdGoods,MdVendorGoods转MdGoodsDto
        MdVendorGoodsDto goodsDto = new MdVendorGoodsDto();

        goodsDto.setGoodsId(mdGoods.getGoodsId());
        goodsDto.setGoodsCode(mdGoods.getGoodsCode());
        goodsDto.setVendorId(vendorId);
        goodsDto.setGoodsName(mdGoods.getGoodsName());

        goodsDto.setVendorGoodsId(vendorGoods.getVendorGoodsId());
        goodsDto.setSpec(vendorGoods.getSpec());
        goodsDto.setPrice(vendorGoods.getPrice());
        goodsDto.setRemark(vendorGoods.getRemark());
        goodsDto.setPacking(vendorGoods.getPacking());
        goodsDto.setShipAddr(vendorGoods.getShipAddr());
        goodsDto.setSupplyArea(vendorGoods.getSupplyArea());
        goodsDto.setSupplyQty(vendorGoods.getSupplyQty());
        goodsDto.setSupplyTime(vendorGoods.getSupplyTime());
        goodsDto.setExpressType(vendorGoods.getExpressType());
        goodsDto.setQualityCode(vendorGoods.getQualityCode());

        return goodsDto;
    }

    /**
     * 修改水果信息
     * @param goods 发布水果表单信息
     * */
    @Transactional
    @Override
    public void  modifyGoods(MdVendorGoodsDto goods) throws Exception{
        // 1.如果goodsCode为空 修改自定义水果
        if (null == goods.getGoodsCode() || "".equals(goods.getGoodsCode().trim())){
            // 1.转换为MdGoods对象
            MdGoods mdGoods = new MdGoods();
            mdGoods.setGoodsId(goods.getGoodsId());
            mdGoods.setGoodsName(goods.getGoodsName());
            mdGoods.setModifyUser(getUserInfo());
            mdGoods.setModifyTime(new Date());

            // 1.2更新水果相关信息
            int rs1 = goodsDao.updateVendorGoods(mdGoods);

            if( 1 != rs1){
                throw new RuntimeException("修改水果信息失败！更新MdGoods表异常。");
            }
        }else {
            // 2.4查询goodsCode对应goodsId
            String result = goodsDao.selectByGoodsCode(goods.getGoodsCode());

            if (null == result){
                throw new Exception("未找到该水果编码！");
            }

        }

        // 2.转换为MdVendorGoods对象
        MdVendorGoods mdVendorGoods = new MdVendorGoods();
        mdVendorGoods.setVendorId(goods.getVendorId());
        mdVendorGoods.setGoodsId(goods.getGoodsId());
        mdVendorGoods.setSpec(goods.getSpec());
        mdVendorGoods.setPrice(goods.getPrice());
        mdVendorGoods.setPacking(goods.getPacking());
        mdVendorGoods.setSupplyQty(goods.getSupplyQty());
        mdVendorGoods.setSupplyArea(goods.getSupplyArea());
        mdVendorGoods.setSupplyTime(goods.getSupplyTime());
        mdVendorGoods.setShipAddr(goods.getShipAddr());
        mdVendorGoods.setExpressType(goods.getExpressType());
        mdVendorGoods.setQualityCode(goods.getQualityCode());
        mdVendorGoods.setRemark(goods.getRemark());
        mdVendorGoods.setModifyUser(getUserInfo());
        mdVendorGoods.setModifyTime(new Date());

        // 4.更新供应商相关信息
        int rs2 = vendorGoodsDao.updateVendorGoods(mdVendorGoods);

        if( 1 != rs2){
            throw new RuntimeException("修改水果信息失败！更新MdVendorGoods表异常。");
        }

    }

    /**
     * 查看历史水果详情
     * @param params 水果名称,水果编码,供应商Id
     * */
    public MdVendorGoodsDto queryGoodsHistory(Map<String,Object> params) throws Exception{
        // 1.参数处理
        int vendorId= 0;
        String goodsName,goodsCode = "";
        try {
            vendorId = Integer.parseInt(params.get("vendorId").toString());
            goodsName = params.get("goodsName").toString();
            goodsCode = null == params.get("goodsCode") ? "" : params.get("goodsCode").toString();
        } catch (NumberFormatException e){
            throw new Exception("参数异常！");
        }

        // 2.查询
        MdVendorGoods vendorGoods = vendorGoodsDao.selectGoodsHistory(params);

        if (null == vendorGoods){
            return null;
        }

        // 3.MdVendorGoods转MdGoodsDto
        MdVendorGoodsDto goodsDto = new MdVendorGoodsDto();

        goodsDto.setGoodsId(vendorGoods.getGoodsId());
        goodsDto.setGoodsCode(vendorGoods.getGoodsCode());
        goodsDto.setVendorId(vendorId);
        goodsDto.setGoodsName(vendorGoods.getGoodsName());

        goodsDto.setSpec(vendorGoods.getSpec());
        goodsDto.setPrice(vendorGoods.getPrice());
        goodsDto.setRemark(vendorGoods.getRemark());
        goodsDto.setPacking(vendorGoods.getPacking());
        goodsDto.setShipAddr(vendorGoods.getShipAddr());
        goodsDto.setSupplyArea(vendorGoods.getSupplyArea());
        goodsDto.setSupplyQty(vendorGoods.getSupplyQty());
        goodsDto.setSupplyTime(vendorGoods.getSupplyTime());
        goodsDto.setExpressType(vendorGoods.getExpressType());
        goodsDto.setQualityCode(vendorGoods.getQualityCode());
        goodsDto.setVendorGoodsId(vendorGoods.getVendorGoodsId());

        return goodsDto;
    }

    /**
     * 获取用户信息
     * */
    public String getUserInfo(){
        try {
            Subject sub = SecurityUtils.getSubject();
            return null == sub.getSession().getAttribute("mdAccount") ? "未登录用户" :
                    ((MdAccount) sub.getSession().getAttribute("mdAccount")).getName();
        } catch (Exception e){
            logger.debug("获取登录用户信息失败！",e);
            return "未登录用户";
        }
    }
}
